package com.cupk.controllers;

import com.cupk.dtos.ChangePasswordRequest;
import com.cupk.dtos.MessageResponse;
import com.cupk.dtos.UpdateUserRequest;
import com.cupk.dtos.UserDto;
import com.cupk.services.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService; // 注入 UserService

    /**
     * 获取所有用户列表，用于前端下拉选择
     */
    @GetMapping
    @PreAuthorize("isAuthenticated()") // 确保只有登录用户才能调用
    public ResponseEntity<List<UserDto>> getAllUsers() {
        // 调用 Service 方法，并返回安全的 DTO 列表
        return ResponseEntity.ok(userService.getAllUsersForSelection());
    }

    /**
     * 获取当前用户的个人资料
     */
    @GetMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<UserDto> getCurrentUserProfile(Authentication authentication) {
        String username = authentication.getName();
        UserDto userProfile = userService.getUserProfile(username);
        return ResponseEntity.ok(userProfile);
    }

    /**
     * 更新当前用户的个人资料
     */
    @PutMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<UserDto> updateCurrentUserProfile(
            @Valid @RequestBody UpdateUserRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        UserDto updatedProfile = userService.updateUserProfile(username, request);
        return ResponseEntity.ok(updatedProfile);
    }

    /**
     * 修改当前用户的密码
     */
    @PutMapping("/change-password")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<MessageResponse> changePassword(
            @Valid @RequestBody ChangePasswordRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        userService.changePassword(username, request);
        return ResponseEntity.ok(new MessageResponse("密码修改成功"));
    }
}